import {Document, Progress, UserGroup, User, Group} from '../../models'
import * as $notify from '../../services/notification'

module.exports = {
  title: '给学生发通知',
  enable: true,
  async run ({versionId, progressId, data, isNeedRedo = false}) {
    let that = this
    if (!data) return
    let document = await Document.findById(versionId)
    let title = document ? document.name : ''
    if (!title) return

    let teacher = await User.findById(document.userId)
    let teacherName = teacher.nickName || '未知老师'

    let progress = await Progress.findById(progressId)
    if (!progress) return
    if (progress.type === 'exercise') return
    let groupId = progress.groupId
    let userId = progress.userId
    let ug = await UserGroup.findOne({
      where: {
        userId,
        groupId
      }
    })
    if (!ug || !ug.name) return

    let group = await Group.findById(groupId)
    let groupName = group.name || '未知班级'

    if (isNeedRedo) {
      await $notify.sendNotification({
        title: '作业待订正提醒',
        data: {
          keyword1: {
            value: title
          },
          keyword2: {
            value: teacherName
          },
          keyword3: {
            value: groupName
          }
        },
        url: 'pages/progress/main?isShowSideMenu=y&progressId=' + progressId
      }, {
        userId
      })
    } else {
      await $notify.sendNotification({
        title: '作业批改完成通知',
        data: {
          keyword1: {
            value: title
          },
          keyword2: {
            value: ug.name
          },
          keyword3: {
            value: getDataText(data)
          }
        },
        url: 'pages/progress/main?isShowSideMenu=y&progressId=' + progressId
      }, {
        userId
      })
    }
  }
}

const getDataText = (data) => {
  let res = ''
  if (data && data.blocks) {
    let blocks = data.blocks
    for (let i = 0; i < blocks.length; i++) {
      let node = blocks[i]
      if (node.type === 'audio') {
        res = '语音点评'
      }
      if (node.type === 'image') {
        res = '图片点评'
      }
      if (node.type === 'video') {
        res = '视频点评'
      }
      if (node.type === 'text') {
        res = node.value
        break
      }
    }
  }
  return res
}
